package cc.geeksearch.ble

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.animation.core.LinearEasing
import androidx.compose.animation.core.animateFloat
import androidx.compose.animation.core.infiniteRepeatable
import androidx.compose.animation.core.rememberInfiniteTransition
import androidx.compose.animation.core.tween
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.Refresh
import androidx.compose.material.icons.filled.Search
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.rotate
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import cc.geeksearch.ble.bean.ScanItemBean

class ScanActivity : ComponentActivity() {
    private val TAG = "ScanActivity"
    private var list = mutableStateListOf<ScanItemBean>()
    private var isRotatingIconVisible by mutableStateOf(false)
    private var isConnectDialogVisible by mutableStateOf(false)
    private var bluetoothIsOpen by mutableStateOf(false)
    private var address: String? = null

    @OptIn(ExperimentalMaterial3Api::class)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContent {
            Scaffold(modifier = Modifier.fillMaxSize(), topBar = {
                TopAppBar(
                    title = { Text(text = stringResource(R.string.add_device)) },
                    colors = TopAppBarDefaults.topAppBarColors(
                        containerColor = MaterialTheme.colorScheme.primaryContainer,
                        titleContentColor = MaterialTheme.colorScheme.primary,
                    ),
                    navigationIcon = {
                        IconButton(onClick = {
                            finish()
                        }) {
                            Icon(
                                imageVector = Icons.AutoMirrored.Filled.ArrowBack,
                                contentDescription = stringResource(R.string.back)
                            )
                        }
                    },
                    actions = {
                        if (isRotatingIconVisible) {
                            val infiniteTransition = rememberInfiniteTransition()
                            val angle by infiniteTransition.animateFloat(
                                initialValue = 0f,
                                targetValue = 360f,
                                animationSpec = infiniteRepeatable(
                                    animation = tween(1000, easing = LinearEasing)
                                )
                            )
                            IconButton(onClick = {
                                // 处理旋转图标点击事件
                                stopScan()
                            }) {
                                Icon(
                                    imageVector = Icons.Default.Refresh,
                                    contentDescription = "旋转图标",
                                    modifier = Modifier.rotate(angle)
                                )
                            }
                        } else {
                            // 添加一个加号图标按钮
                            IconButton(onClick = {
                                startScan()
                            }) {
                                Icon(
                                    imageVector = Icons.Default.Search,
                                    contentDescription = "搜索"
                                )
                            }
                        }

                    },
                )
            }) { innerPadding ->
                DeviceList(baseContext, list, Modifier.padding(innerPadding))
                if (isConnectDialogVisible) {
                    ConnectDialog()
                }
            }
        }

        LiveDataBus.scanLiveData.observe(this) {
            list.clear()
            list.addAll(it)
        }

        LiveDataBus.scanStatusLiveData.observe(this) {
            if (it == 1) {
                isRotatingIconVisible = false // 扫描结束时隐藏旋转图标
            }
        }

        LiveDataBus.deviceStatusLiveData.observe(this) {
            if (address.isNullOrEmpty() || it.address != address) {
                return@observe
            }
            if (it.status == DeviceStatus.CONNECTED) {
                isConnectDialogVisible = true
                Toast.makeText(baseContext, "connection successful!", Toast.LENGTH_SHORT).show()
                finish()
            } else if (it.status == DeviceStatus.DISCONNECTED || it.status == DeviceStatus.CONNECT_FAILED) {
                isConnectDialogVisible = false
                Toast.makeText(baseContext, "connection failed!", Toast.LENGTH_SHORT).show()
            }
        }

        // 监听蓝牙开关状态变化
        val filter =
            android.content.IntentFilter(android.bluetooth.BluetoothAdapter.ACTION_STATE_CHANGED)
        registerReceiver(bluetoothStateReceiver, filter)
    }

    // 监听蓝牙开关状态变化
    val bluetoothStateReceiver = object : android.content.BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            val action = intent.action
            if (action == android.bluetooth.BluetoothAdapter.ACTION_STATE_CHANGED) {
                val state = intent.getIntExtra(
                    android.bluetooth.BluetoothAdapter.EXTRA_STATE,
                    android.bluetooth.BluetoothAdapter.ERROR
                )
                when (state) {
                    android.bluetooth.BluetoothAdapter.STATE_ON -> {
                        // 蓝牙已打开，开始扫描
                        bluetoothIsOpen  = true
                        startScan()
                    }

                    android.bluetooth.BluetoothAdapter.STATE_OFF -> {
                        // 蓝牙已关闭，停止扫描并隐藏旋转图标
                        bluetoothIsOpen  = false
                        stopScan()
                    }
                }
            }
        }
    }

    override fun onResume() {
        super.onResume()
        startScan()
    }

    private fun startScan() {
        if (!WalleUtil.bluetoothIsOpen(baseContext)) {
            return
        }
        Walle.getInstance(baseContext).startScan()
        isRotatingIconVisible = true // 扫描开始时显示旋转图标
    }

    private fun stopScan() {
        WalleLog.w(TAG, "stopScan")
        Walle.getInstance(baseContext).stopScan()
        isRotatingIconVisible = false
    }

    override fun onDestroy() {
        super.onDestroy()
        isConnectDialogVisible = false
        Walle.getInstance(baseContext).stopScan()
        unregisterReceiver(bluetoothStateReceiver)
    }

    @Composable
    fun DeviceList(context: Context, devices: List<ScanItemBean>, modifier: Modifier = Modifier) {
        bluetoothIsOpen = WalleUtil.bluetoothIsOpen(context)
        if (!bluetoothIsOpen) {
            Text(
                text = "Bluetooth is not open",
                color = androidx.compose.ui.graphics.Color.White,
                modifier = modifier
                    .background(androidx.compose.ui.graphics.Color.Red)
                    .fillMaxWidth()
                    .padding(10.dp)
            )
            return
        }

        val scrollState = rememberScrollState()
        Column(
            modifier = modifier.verticalScroll(scrollState)
        ) {
            devices.forEachIndexed { index, deviceItem ->
                Box(
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(70.dp)
                        .padding(10.dp)
                        .clickable {
                            isConnectDialogVisible = true
                            address = deviceItem.address
                            Walle.getInstance(context).connect(deviceItem.device)
                        }) {
                    Text(
                        text = deviceItem.name,
                        fontSize = 18.sp,
                        modifier = Modifier.align(androidx.compose.ui.Alignment.TopStart)
                    )
                    Text(
                        text = deviceItem.address,
                        fontSize = 14.sp,
                        modifier = Modifier.align(androidx.compose.ui.Alignment.BottomStart)
                    )

                    Text(
                        text = deviceItem.rssi.toString(),
                        fontSize = 14.sp,
                        modifier = Modifier.align(androidx.compose.ui.Alignment.CenterEnd)
                    )
                }
                // 在每个设备项之后添加分隔线，除了最后一个设备项
                if (index < devices.size - 1) {
                    androidx.compose.material3.HorizontalDivider()
                }
            }
        }
    }

    @Composable
    fun ConnectDialog() {
        AlertDialog(
            onDismissRequest = {
                isConnectDialogVisible = false
            },
            text = {
                Column {
                    CircularProgressIndicator()
                }
            },
            confirmButton = { /* 这里可以添加确认按钮，根据实际需求 */ },
            dismissButton = { /* 这里可以添加取消按钮，根据实际需求 */ },

            )
    }
}



